package com.quantdo.demo.view;

import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.action.IToolBarManager;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.TreeViewer;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.ui.IActionBars;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.part.DrillDownAdapter;
import org.eclipse.ui.part.ViewPart;

import com.quantdo.demo.date.IElement;
import com.quantdo.demo.date.NavigatorElementFactory;

public class NavigatorView extends ViewPart {

	private TreeViewer treeViewer;
	private DrillDownAdapter drillDownAdapter;
	
	@Override
	public void createPartControl(Composite parent) {
		System.out.printf("class:%s, function:%s() enter \n", NavigatorView.class, "createPartControl");
		treeViewer = new TreeViewer(parent, SWT.MULTI|SWT.H_SCROLL|SWT.V_SCROLL);
		treeViewer.setContentProvider(new TreeViewerContentProvider());
		treeViewer.setLabelProvider(new TreeViewerLabelprovider());
		treeViewer.setInput(NavigatorElementFactory.getTreeElements());
		fillViewToolBarAction();
		fillViewToolBarContextMenu();
		hookDoubleClickAction();
	}

	@Override
	public void setFocus() {
		System.out.printf("class:%s, function:%s() enter \n", NavigatorView.class, "setFocus");
	}

	private void fillViewToolBarAction(){
		IActionBars bars = getViewSite().getActionBars();
		IToolBarManager toolBar = bars.getToolBarManager();
		drillDownAdapter = new DrillDownAdapter(treeViewer);
		drillDownAdapter.addNavigationActions(toolBar);
	}
	private void fillViewToolBarContextMenu(){
		IActionBars actionBars = getViewSite().getActionBars();
		IMenuManager menuManager = actionBars.getMenuManager();
		drillDownAdapter.addNavigationActions(menuManager);
	}
	private void hookDoubleClickAction(){
		System.out.printf("class:%s, function:%s() enter \n", NavigatorView.class, "hookDoubleClickAction");
		treeViewer.addDoubleClickListener(evn->{
			System.out.printf("class:%s, function:%s() enter \n", NavigatorView.class, "~hookDoubleClickAction");
			String editorId="com.quantdo.demo.edit.NavigatorEdit";//NavigatorEdit.class.getName();
			ISelection select = treeViewer.getSelection();
			IElement eleObj = (IElement)((IStructuredSelection)select).getFirstElement();
			IWorkbenchPage workbenchPage = getViewSite().getPage();
			IEditorPart editor = workbenchPage.findEditor(eleObj.getEditorInput());
			if(null != editor){
				workbenchPage.bringToTop(editor);
			}
			else{
				try {
					workbenchPage.openEditor(eleObj.getEditorInput(), editorId);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}
	
}
